package threadcontrol;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * 
 * CyclicBarrier与CountDownLatch较为类似，都是等到一定数目的线程后才进行下一步
 * 1. 但是CyclicBarrier是通过CyclicBarrier.await()进入等待状态的，而CountDownLatch是通过CountDownLatch.countDown()标记的
 * 2. CyclicBarrier是一组线程先到等待后到，CountDownLatch是主线程等待所有子线程运行完
 * 
 * @author lcx
 *
 */
public class CyclicBarrierTest {
	public static void main(String[] args) {
		int N = 4;
		CyclicBarrier barrier  = new CyclicBarrier(N);
		for(int i=0;i<N;i++)
			new Writer(barrier).start();
	}
	static class Writer extends Thread{
		private CyclicBarrier cyclicBarrier;
		public Writer(CyclicBarrier cyclicBarrier) {
			this.cyclicBarrier = cyclicBarrier;
		}

		@Override
		public void run() {
			System.out.println("线程"+Thread.currentThread().getName()+"正在写入数据...");
			try {
				Thread.sleep(5000);      //以睡眠来模拟写入数据操作
				System.out.println("线程"+Thread.currentThread().getName()+"写入数据完毕，等待其他线程写入完毕");
				cyclicBarrier.await();
				System.out.println("线程"+Thread.currentThread().getName()+"结束wait");
			} catch (InterruptedException e) {
				e.printStackTrace();
			}catch(BrokenBarrierException e){
				e.printStackTrace();
			}
			//            System.out.println("所有线程写入完毕，继续处理其他任务...");
		}
	}
}

